import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zchope_student/beans/signbean.dart';
import 'package:zchope_student/beans/subjectsbean.dart';
import 'package:zchope_student/utils/fluro.dart';
import 'package:zchope_student/utils/mydio.dart';
import 'package:zchope_student/utils/utils.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class LessonsOnline extends StatefulWidget {
  @override
  _LessonsOnlineState createState() => _LessonsOnlineState();
}

class _LessonsOnlineState extends State<LessonsOnline> {
  SharedPreferences sp;
  var _studyMin;
  var titles1 = List();
  var titles4 = List();
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  var checkString = '';
  static final COURSE_DURATION_MAX = 240;
  static final COURSE_DURATION_MIN =10;
  var password = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldkey,
      backgroundColor: Const.black,
      appBar: AppBar(
        title: Text(
          '课程列表',
        ),
        actions: <Widget>[
          FlatButton(
            child: Text(
              Utils.getInstance().checkEmpty(password) ? '签到' : '签退',
              style: TextStyle(color: Const.gold),
            ),
            onPressed: () {
              var code = Utils.getInstance().checkLogin();
              code.then((onValue) {
                if (onValue == Const.UNSIGN) {
                  Routes.router.navigateTo(context, Routes.loginMain,
                      replace: false, transition: TransitionType.fadeIn);
                } else if (onValue == Const.UNBIND) {
                  Routes.router.navigateTo(context, Routes.userBind,
                      replace: false, transition: TransitionType.fadeIn);
                } else {
                  if (Utils.getInstance().checkEmpty(password)) {
                    _takePhoto(Const.SIGN_IN, 0);
                  } else {
                    var duration = sp.getInt(Const.STUDY_MIN) ~/ 60;
                    if (duration < COURSE_DURATION_MIN) {
                      Utils.getInstance().showSnackBar(
                          _scaffoldkey, '培训时长不足$COURSE_DURATION_MIN分钟!');
                      return;
                    }
                    _takePhoto(Const.SIGN_OUT, duration);
                  }
                }
              });
            },
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        children: <Widget>[
          Column(
            children: <Widget>[
              Item(
                title: '科目一',
                value: 10,
                totalValue: 30,
                widgetList: _setWidgetList('科目1', titles1),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: Divider(
                  height: 1,
                  color: Const.grey,
                ),
              ),
              Item(
                title: '科目四',
                value: 75,
                totalValue: 100,
                widgetList: _setWidgetList('科目4', titles4),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    _setData();
    MyDio.getInstance().clearInstance();
    MyDio.getInstance(url: Const.TESTURL).get(Apis.subjectList, (data) async {
      print(data);
      if (data['status'] == 200) {
        SubjectsBean subjectsBean = SubjectsBean.fromJson(data['data']);
        titles1 = subjectsBean.subject1;
        titles4 = subjectsBean.subject4;
        setState(() {});
      }
    });
  }

  // 拍照
  _takePhoto(var sign, var duration) async {
//    print('password===:${password}');
//    print('subject===${sp.getInt(Const.SUBJECT)}');
    File image = await ImagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: 480,
        maxHeight: 600,
        imageQuality: 100);
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    checkString = Utils.getInstance()
        .getSha256(sp.get(Const.PERSON_NUM), sp.getString(Const.PERSON_NUM));

    FormData data = FormData.fromMap({
      'userid': sp.get(Const.PERSON_NUM), //用户
//      'duration': duration, //培训时间
      'duration': 240, //培训时间
      'sign': sign, //签到 签退
      'subject': sp.getInt(Const.SUBJECT), //科目
      'course': sp.getString(Const.COURSE), //课程
      'pass': password,
      'check': checkString, //校验
      'file': await MultipartFile.fromFile(path, filename: name)
    });
    MyDio.getInstance(url: Const.TESTURL)
        .upload('${Apis.upload}${sp.get(Const.AREA_CODE)}', (data) async {
      print(data);
      if (data['errorcode'] == 0) {
        Utils.getInstance().showSnackBar(_scaffoldkey, '上传成功');
        sp.setInt(Const.STUDY_MIN, 0);
        if (sign == Const.SIGN_IN) {
          // 签到 储存
          print('data:${data['data']}');
          SignBean signBean = SignBean.fromJson(data['data']);
          password = signBean.pass;
          sp.setString(Const.PASS, password);

          setState(() {});
        } else if (sign == Const.SIGN_OUT) {
          // 签退 清空
          _clearTraining();
          setState(() {});
        }
      } else if (data['errorcode'] == 1) {
        Utils.getInstance().showSnackBar(_scaffoldkey, '照片识别失败');
//        _takePhoto(sign, duration);
      }
    }, params: data);
  }

  // 结束培训后清空
  _clearTraining() {
    sp.clear();
    sp.setInt(Const.SUBJECT, -1);
    sp.setString(Const.COURSE, '');
    password = '';
    sp.setString(Const.PASS, password);
  }

  _setWidgetList(String head, List titles) {
    List<Widget> dataList = List();
    for (Subject1 bean in titles) {
      String courseId = bean.courseName.substring(0, 2);
      var item = GestureDetector(
        onTap: () {
          var code = Utils.getInstance().checkLogin();
          code.then((onValue) {
            Utils.getInstance().showSnackBar(_scaffoldkey, bean.videoName);
            if (onValue == Const.UNSIGN || onValue == Const.UNBIND) {
              String route =
                  '${Routes.myIjkPlayer}?url=${FluroConvertUtils.fluroCnParamsEncode(bean.videoUrl)}';
              Routes.router.navigateTo(context, route,
                  replace: false, transition: TransitionType.fadeIn);
            } else {
              // 本地化科目及课程
//              print('bean.subjectId===${bean.subjectId}');
//              print('bean.subject===${bean.subject}');
              sp.setInt(Const.SUBJECT, bean.subject);
              sp.setString(Const.COURSE, courseId);

              // 没有 pass 认为没有签到
              if (Utils.getInstance().checkEmpty(password)) {
                _takePhoto(Const.SIGN_IN, 0);
                return;
              }

              var duration = sp.getInt(Const.STUDY_MIN) ~/ 60;
              if (duration > COURSE_DURATION_MAX) {
                Utils.getInstance().showSnackBar(
                    _scaffoldkey, '单次培训超过$COURSE_DURATION_MAX分钟,本次学时不记录.');
              }
            }
            String route =
                '${Routes.myIjkPlayer}?url=${FluroConvertUtils.fluroCnParamsEncode(bean.videoUrl)}';
            Routes.router.navigateTo(context, route,
                replace: false, transition: TransitionType.fadeIn);
          });

        },
        child: SizedBox(
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 20),
            child: Text(
              '[$head] ${bean.videoJianjie}',
              style: TextStyle(color: Const.gold, fontSize: 14),
            ),
          ),
        ),
      );
      dataList.add(item);
    }
    return dataList;
  }

  _setData() async {
    _studyMin = await _getStudyMin();
    // 如果没就设置0
    if (_studyMin == null) {
      sp.setInt(Const.STUDY_MIN, 0);
      _studyMin = 0;
    }
    _getLessonsOnline();
    _studyMin = _studyMin ~/ 60;

    if (_studyMin > COURSE_DURATION_MAX) {
      Utils.getInstance()
          .showSnackBar(_scaffoldkey, '单次培训时长不能超过COURSE_DURATION分钟');
      _takePhoto(Const.SIGN_OUT, _studyMin);
    }
  }

  _getStudyMin() async {
    sp = await SharedPreferences.getInstance();
    password = sp.get(Const.PASS);
    return sp.getInt(Const.STUDY_MIN);
  }

  _getLessonsOnline() {
    print('_studyMin:$_studyMin');
  }
}

class Item extends StatelessWidget {
  final title;
  final value;
  final totalValue;
  final widgetList;

  const Item(
      {Key key, this.title, this.value, this.totalValue, this.widgetList})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              SizedBox(
                width: 260,
                child: Text(
                  title,
                  softWrap: true,
                  style: TextStyle(fontSize: 20, color: Const.gold),
                ),
              )
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Seek(
            value: value,
            totalValue: totalValue,
            length: 300.0,
            height: 17.0,
          ),
          SizedBox(
            height: 15,
          ),
          Text(
            '课程内容',
            style: TextStyle(fontSize: 16, color: Const.gold),
          ),
          SizedBox(
            height: 5,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: widgetList,
          )
        ],
      ),
    );
  }
}

class Seek extends StatelessWidget {
  final value;
  final totalValue;
  final length;
  final height;

  const Seek({Key key, this.value, this.totalValue, this.length, this.height})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    print('value:$value');
    print('totalValue:$totalValue');
    return SizedBox(
      height: 40,
      width: length,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 0,
            bottom: 0,
            child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                child: Container(
                  width: length,
                  height: height,
                  color: const Color(0xffF0F0F0),
                )),
          ),
          Positioned(
            left: 0,
            bottom: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Text(
                  '剩余${totalValue - value}分钟',
                  style: TextStyle(
                    fontSize: 14,
                    color: Const.gold,
                  ),
                ),
                SizedBox(height: 5),
                ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                    child: Container(
                      width: length * value / totalValue,
                      height: height,
                      color: Const.gold,
                    )),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
